(ns xuan-clj.routes.manage
  (:require [xuan-clj.middleware :as middleware]
            [xuan-clj.db.core :as db]
            [xuan-clj.middleware.wrappers :refer :all]
            [ring.util.http-response :as response]
            [clojure.string :as str]
            [xuan-clj.service.token :as token]
            [clj-time.core :refer :all]))

(defn- get-user-by-username [username]
  (db/get-user-by-username {:username username}))

;;; 登录接口
(defn login [{:keys [params]}]
  (let [{:keys [username password]} params]
    #_(println username password)
    (if
      ;; 用户名或密码为空
      (or (str/blank? username)
          (str/blank? password))
      (wrap-error-response "用户名或密码为空")
      (let [user (get-user-by-username username)]
        (cond
          ;; 用户不存在
          (empty? user)
          (wrap-error-response "用户名或密码错误")

          ;; 密码错误
          (not= password (:password user))
          (wrap-error-response "用户名或密码错误")

          ;; 登录成功，返回token
          :else
          (-> username token/create-token wrap-ok-response))))))

;;; 人员信息接口
(defn profile [{:keys [headers] :as request}]
  (let [token (get headers "token")
        username (token/decode-token token)
        user (get-user-by-username username)
        nickName (str (:first_name user) " " (:last_name user))]

    (response/ok {:resultCode 200 :msg "操作成功" :data {:loginUserName username :nickName nickName}})
    ))

;;; 查询所有用户
(defn users [{:keys [params] :as request}]
  (println params)
  (response/ok {:resultCode 200 :msg "操作成功" :data "abc"})
  )

;;; 查询所有文档
(defn docs [{:keys [params] :as request}]
  (let [{:keys [pageNumber pageSize]} params
        m (* (Integer/parseInt pageSize) (dec (Integer/parseInt pageNumber)))
        n (Integer/parseInt pageSize)]
    (->> (db/get-docs {:m m :n n})
         (wrap-page 10 pageNumber)
         (wrap-ok-response)
         )
    )
  )

(defn manage-routes-no-verify-token []
  ["/manage-api/v1"
   {:middleware [middleware/wrap-formats]}
   ["/adminUser/login" {:post login}]
   ]
  )

;;; 修改密码
(defn password [{:keys [params headers]}]
  (let [{:keys [originalPassword newPassword]} params
        token (get headers "token")
        username (token/decode-token token)
        user (get-user-by-username username)]
    (if (= originalPassword (:password user))
      (do
        (db/update-user! (-> user (assoc :password newPassword) (assoc :updated_by username)))
        (wrap-ok-response "修改成功")
        )
      ;; 原密码错误
      (wrap-error-response "原密码错误")
      )
    ))

(defn manage-routes []
  ["/manage-api/v1"
   {:middleware [middleware/wrap-formats wrap-verify-token]}
   ["/adminUser/profile" {:get profile}]
   ["/adminUser/password" {:put password}]
   ["/users" {:get users}]
   ["/docs" {:get docs}]
   ]
  )
